# Multi-stage build for LockNKey Vault Service
FROM node:18-alpine AS builder

# Set working directory
WORKDIR /app

# Install build dependencies
RUN apk add --no-cache python3 make g++ git curl

# Copy package files
COPY package*.json ./
COPY tsconfig.json ./

# Install all dependencies (including dev dependencies for build)
RUN npm ci && npm cache clean --force

# Copy source code
COPY src/ ./src/

# Build TypeScript
RUN npm run build

# Production stage
FROM node:18-alpine AS production

# Install curl for health checks
RUN apk add --no-cache curl

# Create lockkey user for security
RUN addgroup -g 1001 -S lockkey && \
    adduser -S lockkey -u 1001

# Set working directory
WORKDIR /app

# Install production dependencies only
COPY package*.json ./
RUN npm ci --only=production && npm cache clean --force

# Copy built application from builder
COPY --from=builder /app/dist ./dist

# Copy any additional files needed
COPY .env.example ./

# Set ownership to lockkey user
RUN chown -R lockkey:lockkey /app

# Switch to non-root user
USER lockkey

# Expose port
EXPOSE 8002

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
  CMD curl -f http://localhost:8002/health || exit 1

# Environment variables
ENV NODE_ENV=production
ENV PORT=8002

# Start application
CMD ["node", "dist/index.js"]